//
//  YMSComposeController.swift
//  YMSWeibo
//
//  Created by 杨茂盛 on 2016/11/21.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit
private let baseTag = 100
//定义枚举 作为toolbar里面按钮的点击事件
enum YMSCoposeType:Int{
    case Picture = 100
    case AtSome
    case Topic
    case Emotion
    case More
}
class YMSComposeController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1)
        //添加左边按钮
        addLeftBarButton()
        //添加右边按钮
        addRightBarButton()
        //添加导航栏标题
        setNavgationBarTitle()
        //添加textView
        addTextView()
        //添加toolBar
        setToolBar()
        //注册通知
        registeNotification()
        //添加图片选择控制器
        setSelectorPictureController()
        self.view.bringSubview(toFront: toolBar) //把toolbar移动到顶层
    }
    
    //MARK:
    //MARK: 给导航栏添加左边按钮
    private func addLeftBarButton(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: "", target: self, action: #selector(clickLeftBarBtn))
    }
    private func addRightBarButton(){
        self.navigationItem.rightBarButtonItem = sendBtn
    }
    //左边按钮的点击事件
    @objc internal func clickLeftBarBtn(){
        dismiss(animated: true, completion: nil)
    }
    
    //图片选择控制器
    lazy var addPictureVc:YMSAddPictureController = {
        let flow = UICollectionViewFlowLayout()
        let margin:CGFloat = 8
        let itemWidth = (ScreenWidth - (4*margin)) / 3
        flow.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flow.scrollDirection = .vertical
        flow.minimumLineSpacing = margin
        flow.minimumInteritemSpacing = margin
        flow.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        let Vc = YMSAddPictureController(collectionViewLayout: flow)
        Vc.collectionView?.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        return Vc
    }()
    
    //添加图片选择控制器
    func setSelectorPictureController(){
        //添加子视图控制器
        self.addChildViewController(self.addPictureVc)
        //添加子视图控制器的视图
        self.view.addSubview(addPictureVc.view)
        //约束
        addPictureVc.view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(ScreenHeight/3*2)
        }
    }

    
    //MARK: 右边按钮监听事件
    func sendBtnDidClick(){
        print("发表")
        
        /*
         需要将文本中的表情图片转换为chs发送 服务器
         如果属性文本中包含图片 属性中就会包含NSAttachment 这个key会对应一个附件对象
         
         */
        //遍历文本的属性
//        var strM = String()
//        myTextView.attributedText.enumerateAttributes(in: NSMakeRange(0, myTextView.attributedText.length), options: [], using: {(dict,range,_) -> () in
            //print(dict) // 包含当前页对应的20个表情
            //print(NSStringFromRange(range))
            
//            //取出附件对象
//            if let attachment = dict["NSAttachment"] as? HMTextAttachment{
//            
//           print(attachment.chs)//所选择的表情
//             strM += attachment.chs ?? ""
//                
//            }else{
//            //文字或者emoji
//                let sub = (self.myTextView.text as NSString).substring(with: range)
//                strM += sub
//            }
//            
//        })
//        print(strM)
        
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        //POST请求不需要做urlEncode 只有get请求需要处理
        let parameters = ["access_token":YMSUserinfoViewModel.shared.userAccount?.access_token,"status":myTextView.imageEmoticon2Chs()]
        SVProgressHUD.show() //点击发表后页面会显示加载状态,让用户直到当前在发
        if addPictureVc.pictureArray.count == 0 {
            YMSNetWorkToll.shared.request(method: .POST, urlString: urlString, parameters: parameters, finished: { (responde,error) -> () in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发表失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发表成功")
            })
        }else{
        //发表图片
            //发表图片里的接口 可在新浪微博的文档中找到
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //拼接参数 发表图片和文字不同,要拼接如下数据：
            
            //将需要上传的文件的二进制数据拼接到formdata中
            //withFileData: 需要上传的文件的二进制数据
            //name: 服务器接收的字段 "pic"
            //fileName: 服务器存储的名称, 不过新浪微博的服务器会对用户上传的图片按照自己的规则进行处理
            //mimeType: 标识文件类型
         
                YMSNetWorkToll.shared.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                    for item in self.addPictureVc.pictureArray {
                        // print(item)
                        //发表多图
                        let imageData = UIImagePNGRepresentation(item)
                        formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "\(Data())", mimeType: "application/octet-stream")
                    }
                }, progress: nil, success: { (_, result) in
                    SVProgressHUD.showSuccess(withStatus: "发表成功")
                    
                }, failure: { (_, error) in
                    print(error)
                    SVProgressHUD.showError(withStatus: "发表失败")
                })
        }
    }
    
    //在视图将要出现的时候判断是否隐藏图片选择控制器
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.addPictureVc.view.isHidden = self.addPictureVc.pictureArray.count == 0
        
    }
    
    //MARK: 注册通知
    private func registeNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //注册自定义键盘的通知
        NotificationCenter.default.addObserver(self, selector: #selector(clickEmoji(n:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
    }
    
    //自定义键盘的通知的监听方法
    @objc private func clickEmoji(n:Notification){
        let em = n.object as? HMEmoticon
        myTextView.inputEmoticon(emoticon:em!)
//        guard let emoji = n.object as? HMEmoticon else{
//            //如果点击的不是emoji,就是删除
//            //执行回删
//            myTextView.deleteBackward()
//            return
//        }
//        if emoji.type == 1{
//            //将emoji表情添加到对应的文本中
//            myTextView.replace(myTextView.selectedTextRange!, withText: emoji.emojiStr ?? "")
//            return
//        }
//        
//        
//        //处理图片表情
//        //myTextView.inputEmoticon(em: emoji)
//        
//        //通过附件对象实例化属性字符串
//        //实例化附件对象,将图片包装到附件对象中
//        let attachment = HMTextAttachment()
//        attachment.chs = emoji.chs
//        let lineHeight = myTextView.font!.lineHeight
//        //frame 是相对父控件的 bounds相对于自己的  scrollView能够滚动实际上修改的是自己的bounds,contentOffset 实际上就是 bounds.origin
//        attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight) //不设置bouds,图片会异常的大
//        attachment.image = UIImage(named: emoji.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
//        //通过实例化附件对象实例化一个可变的属性字符串(后面需要给它添加属性)imageText
//        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//        //需要给附件属性文本添加属性
//        imageText.addAttributes([NSFontAttributeName:myTextView.font!], range: NSRange(location: 0, length: 1))
//        //获取当前文本输入视图可变的属性字符串 strM
//        let strM = NSMutableAttributedString(attributedString: myTextView.attributedText)
//        //在替换属性文本之前,先记录光标选中的位置
//        let range = myTextView.selectedRange
//        //将imageText替换到strM对应的光标位置
//        strM.replaceCharacters(in: myTextView.selectedRange, with: imageText)
//        //将strM赋值给myTextView.attributedText
//        myTextView.attributedText = strM
//        //光标恢复到之前选中的位置
//        myTextView.selectedRange = NSRange(location: range.location+1, length: 0) //location必须+1 否则光标一直在原来的位置不会发生变化
//        //输入图片里的是否无法调用代理方法 手动调用
//        myTextView.delegate?.textViewDidChange?(myTextView)
//        
        
    }
    //MARK: 监听通知的变化
    @objc private func keyboardChanged(n:Notification){
        
        let endFrame = n.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        //print(endFrame)
        //让底部toolBar能够移动
        let offsetY = -(ScreenHeight - endFrame.origin.y)
        //print(endFrame.origin.y)
        //print(offsetY)
        
        //更新约束
        UIView.animate(withDuration: 0.25) {
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY)
            })
            //强制刷新界面
            self.view.layoutIfNeeded()
        }
    }
    //MARK: 懒加载底部工具条
    lazy var toolBar:UIStackView = {
        let bottomBar = UIStackView()
        //设置方向
        bottomBar.axis = .horizontal
        //设置填充的方式
        bottomBar.distribution = .fillEqually
        return bottomBar
    }()
    
    //MARK: 添加toolBar
    func setToolBar(){
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        toolBar.backgroundColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
        //添加按钮图片
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        //循环创建按钮
        for (index,imageName) in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage(named:imageName), for: .normal)
            btn.backgroundColor = UIColor.init(white: 0.96, alpha: 1)
            btn.sizeToFit()
            self.toolBar.addArrangedSubview(btn) //添加方式不同
            //添加按钮的监听事件
            btn.addTarget(self, action: #selector(clickToolBarBtn(btn:)), for: .touchUpInside)
            //设置tag的值
            btn.tag = index + baseTag
        }
    }
    //MARK: 按钮的监听方法
    @objc internal func clickToolBarBtn(btn:UIButton){
        //通过原始值获取枚举对象 不能够判断可选类型的枚举值
        let enumType = YMSCoposeType.init(rawValue: btn.tag)!
        switch enumType {
        case .Picture:
            print("选择了图片")
            addPictureVc.clickAddPicture(cell:nil)
        case .AtSome:
            print("@某人")
        case .Topic:
            print("话题")
        case .Emotion:
            print("选择表情")
            if !myTextView.isFirstResponder{
             self.myTextView.becomeFirstResponder()
            }
            self.myTextView.inputView = (myTextView.inputView == nil ? keyboardView : nil)
            myTextView.reloadInputViews()
        case.More:
            print("更多")
        }
    }
    //懒加载textView
    lazy var myTextView:UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.textColor = UIColor.darkGray
        tv.delegate = self
        tv.text = "我是小王"
        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
        return tv
    }()
    
    //MARK: 占位文本的添加
    lazy var placeHolderLabel:UILabel = {
    let myLabel = UILabel()
//        myLabel.text = "请输入您要发表的内容哟😋"
        myLabel.textColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
        return myLabel
    }()
    
    //添加textView
    func addTextView(){
        self.view.addSubview(myTextView)
        //为textView添加占位文字
        self.myTextView.addSubview(placeHolderLabel)
        
        myTextView.snp.makeConstraints { (make) in
            make.height.equalTo(ScreenHeight / 3)
            make.top.left.right.equalTo(self.view)
        }
        
        placeHolderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(myTextView).offset(8)
            make.left.equalTo(myTextView).offset(5)
        }
    }
    
    //MARK: 添加自定义键盘
    lazy var keyboardView :HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 220))
    
    //MARK: 修改导航栏标题
    func setNavgationBarTitle(){
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        if let userName = YMSUserinfoViewModel.shared.userAccount?.name {
            let titleText = "发布微博\n\(userName)"
            titleLabel.text = titleText
            //修改属性文本的属性 用可变的属性文本(不可变的不能添加属性)
            let strM = NSMutableAttributedString(string: titleText)
            //获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            //给用户名添加属性
            strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.orange], range: range)
            //给label的属性文本赋值
            titleLabel.attributedText = strM
        }else{
        titleLabel.text = "发布微博"
        }
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
    }
    //MARK: 自定义导航栏右边按钮
    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
        return barButtonItem
    }()
}

extension YMSComposeController:UITextViewDelegate{

    func textViewDidChange(_ textView: UITextView) {
        //判断发布微博按钮的状态
        sendBtn.isEnabled = textView.hasText
        placeHolderLabel.isHidden = textView.hasText
    }
}
